package com.hspedu.arrays;

import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/2/4
 * @time 20:28
 */
public class ArraysSortCustom {
    public static void main(String[] args) {
        int[] arr = {1, 2321, 43, 431, 4, 7};
        bubbleSort(arr);
        System.out.println(Arrays.binarySearch(arr, 431));

        bubbleSort2(arr, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                int i1 = (Integer) o1;
                int i2 = (Integer) o2;
                // i1 - i2 > 0 等价于 i1 > i2
                // i2 - i1 > 0 等价于 i2 > i1
                //这一步就相当于bubbleSort中 if 判断
                return i1 - i2;
            }
        });
    }

    //使用冒泡排序
    public static void bubbleSort(@NotNull int[] arr) {
        int temp = 0;
        for (int i = 1; i <= arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    //从小到大 arr[j] - arr[j + 1] > 0
                    //从大到小 arr[j + 1] - arr[j] > 0
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }


    public static void bubbleSort2(int[] arr, Comparator c){
        int temp = 0;
        for (int i = 1; i <= arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i; j++) {
                if (c.compare(arr[j],arr[j+1]) > 0) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}
